<template>
  <div>
    <div class="row-header">
      <!--查询条件-->
      <el-form :inline="true" :model="form" :rules="rules" ref="form"  label-width="50px" >
        <el-form-item label=" " prop="loginName">
          <el-autocomplete class="inline-input" size="small" v-model="form.loginName"
                           :fetch-suggestions="querySearch" :trigger-on-focus="false"
                           @select="handleSelect" placeholder="请输入代理账号" clearable>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label=" " prop="passage">
          <el-select filterable v-model="form.passage" placeholder="请选择通道"  >
            <el-option
              v-for="item in passageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " prop="mealType">
          <el-select filterable v-model="form.mealType" placeholder="请选择套餐大类"  >
            <el-option
              v-for="item in mealTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item filterable label=" " prop="balancePackage">
          <el-select v-model="form.balancePackage" placeholder="请选择余额套餐"  >
            <el-option
              v-for="item in balancePackageOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " prop="operationTypeName">
          <el-input placeholder="请输入操作类型" v-model="form.operationTypeName" @focus="dialogFormVisible = true"  suffix-icon="el-icon-arrow-down"></el-input>
        </el-form-item>
        <el-form-item label=" " prop="operationStatus">
          <el-select v-model="form.operationStatus" placeholder="请选择操作状态"  >
            <el-option
              v-for="item in operationStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label=" " prop="operatorName">
          <el-input placeholder="请输入操作人姓名" v-model="form.operatorName" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label=" " prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="插入时间起始日期"
            end-placeholder="插入时间结束日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button type="shenda" size="mini" @click="resetForm('form')"><i class="el-icon-refresh"></i> 重置</el-button>
        <el-button type="shenda" size="mini" @click="page=1;innitData();"><i class="el-icon-search"></i> 查询</el-button>
      </div>
    </div>
    <div class="split-line"></div>
    <div class="row-main">
      <router-link to="/special/bulkOprationCenter"><el-button type="shenda" size="mini" icon="el-icon-receiving">批量操作</el-button></router-link>
      <router-link to="/recycleBinRecord"><el-button type="shenda" size="mini" icon="el-icon-delete" style="margin-left: 10px">前往回收站</el-button></router-link>
      <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }" :data="list"
                ref="table" tooltip-effect="dark" class="row-main-table"
                v-loading.fullscreen="tableLoading" element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)">
        <el-table-column prop="loginName" label="代理账号" align="center"></el-table-column>
        <el-table-column prop="startCardNumber" label="起始卡号" align="center"></el-table-column>
        <el-table-column prop="endCardNumber" label="结束卡号" align="center"></el-table-column>
        <el-table-column prop="dictUserCardTypeName" label="卡类型" align="center"></el-table-column>
        <el-table-column prop="setMealHeadName" label="套餐名称" align="center"></el-table-column>
        <el-table-column prop="balanceHeadName" label="余额套餐名称" align="center"></el-table-column>
        <el-table-column prop="dictOprationTypeName" label="操作类型" align="center"></el-table-column>
        <el-table-column prop="oprationStatus" label="状态" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.oprationStatus=='TASK_COMPLETED'">已完成</span>
            <span v-if="scope.row.oprationStatus=='TASK_PENDING'">进行中</span>
          </template>
        </el-table-column>
        <el-table-column prop="allCount" label="总数" align="center"></el-table-column>
        <el-table-column prop="successCount" label="成功数" align="center"></el-table-column>
        <el-table-column prop="errorCount" label="失败数" align="center"></el-table-column>
        <el-table-column prop="empName" label="操作人" align="center"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center" width="150px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top">
              <span style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis">{{scope.row.remark}}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="insertTimeTime" label="插入时间" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
            <span class="el-dropdown-link">
               <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
            </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="scope.row.dictOprationType==='QR_CODE'"><el-button class="operation" @click="downLoadQRCode(scope.row)">Excel下载</el-button></el-dropdown-item>
                <el-dropdown-item ><el-button class="operation" @click="openExcelDialog(scope.row)">下载全部卡号</el-button></el-dropdown-item>
                <el-dropdown-item v-if="scope.row.errorCount>0"><el-button class="operation" @click="checkErrorData(scope.row)" >查看失败卡号</el-button></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination
          background
          @size-change="changeSize"
          @current-change="changPage"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,50,100]"
          :page-size="pageSize"
          :current-page="page"
          :total="total"
          class="row-main-pager">
        </el-pagination>
      </div>
    </div>
    <el-dialog title="选择操作类型" :visible.sync="dialogFormVisible" :width="$store.state.app.screenWidth<700?'100%':'700px'">
      <el-radio-group v-model="form.operationType" >
        <el-radio :label="item.value" v-for="item in operationTypeOptions" :key="item.value" style="margin: 15px; width: 150px">{{item.label}}</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOperationType">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="未成功卡号列表" :visible.sync="dialogTableVisible" width="70%" center>
      <el-table
        :data="errorList"
        :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }"
        class="row-main-table">
        <el-table-column
          prop="cardNumber"
          label="业务号码"
          align="center"
          >
        </el-table-column>
        <el-table-column
          prop="iccid"
          label="ICCID"
          align="center">
        </el-table-column>
        <el-table-column
          prop="imsi"
          label="IMSI"
          align="center">
        </el-table-column>
        <el-table-column
          prop="msisdn"
          label="MSISDN"
          align="center">
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center">
          <template slot-scope="scope">
            <div style="width:100%;display: flex;align-items: center;cursor: pointer">
              <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top">
                <span class="shotRemark">{{scope.row.remark}}</span>
              </el-tooltip>
              <i class="el-icon-s-order copy-icon" @click="CopyRemark(scope.row.remark)">复制</i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        @current-change="changeErrorPage"
        :page-size="pageSize"
        :page="errorPage"
        :total="errorTotle"
      style="text-align: right;margin-top:20px">
      </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!--可选择下载表格的局中弹窗-->
    <el-dialog
      title="Excel下载"
      :visible.sync="excelDialogVisible"
      width="500px"
      center>
      <div>
        <div v-for="(item,i) in exlList" style="margin-top: 5px;display: flex;justify-content: space-between">
          <span v-if="i === exlList.length-1">第 {{i*60000+1}} 条 至 第 {{exlLength}} 条数据</span>
          <span v-if="i<exlList.length-1">第 {{i*60000+1}} 条 至 第 {{(i+1)*60000}} 条数据</span>
          <el-button type="success" @click="downLoadData(item)" size="small">excel下载</el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="excelDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {
    initSetMealHeadSelect,
    initAccountSelect,
    getbalanceHeadSelect,
    BulkOperateCardsRecords,
    cardNumberRecords,
    excelRecords,
    getLoginName
  } from '@/api/getData'

  export default {
    name: "index",
    data() {
      return {
        form: {
          passage: '',          //通道
          mealType: '',         //套餐大类
          balancePackage: '',   //余额套餐
          operatorName: '',     //操作人姓名
          operationStatus: '0', //操作状态
          dateRange: '',        //插入时间区间
          operationType: '0',   //操作类型id
          operationTypeName: '请选择操作类型',//操作类型名称
          loginName: '',           //代理账号
        },
        formDisabled: false,    //上传表格后查询条件disabled
        passageOptions: [],     //通道下拉列表
        mealTypeOptions: [],    //套餐大类列表
        balancePackageOptions: [],//套餐大类列表
        cardStatusOptions: [],  //卡状态列表
        operationStatusOptions: [//操作状态列表
          {value: '0', label: '请选择操作状态'},
          {value: 'TASK_PENDING', label: '进行中'},
          {value: 'TASK_COMPLETED', label: '已完成'},
        ],
        loginNames: [],
        operationTypeOptions: [
          {value: '0', label: '默认'},
          {value: 'SET_BALANCE', label: '修改余额'},
          {value: 'QR_CODE', label: '导出二维码信息'},
          {value: 'BATCH_OPEN_CARD', label: '批量开机'},
          {value: 'REALNAME', label: '实名'},
          {value: 'REMOVE_REALNAME', label: '取消实名'},
          {value: 'RECYCLE_BIN_CARD', label: '批量放入回收站'},
          {value: 'DISABLED', label: '禁用'},
          {value: 'SETMEAL', label: '设置套餐'},
          {value: 'SET_BALANCE_HEAD', label: '设置余额套餐'},
          {value: 'REMOVE_DISABLED', label: '解禁'},
          {value: 'SET_BUY_IN_AMOUNT', label: '充值余额'},
          {value: 'REMOVE_BUY_IN_AMOUNT', label: '取消充值余额'},
          {value: 'RETURN_CARD', label: '回收卡'},
          {value: 'CHANGE_CARD', label: '设置换卡'},
          {value: 'RESERVE_CARDS', label: '设置备用卡'},
          {value: 'BATCH_FREEFLOW', label: '赠送流量'},
          {value: 'REMOVE_CHANGECARD', label: '取消换卡'},
          {value: 'REMOVE_RESERVE_CARDS', label: '取消备用卡'},
          {value: 'REMARKS_CARD', label: '添加卡备注'},
          {value: 'EXPORT_CARD', label: '批量导出'},
        ],  //操作类型列表
        rules: {
          startNo: [
            {
              validator: (rule, value, callback) => {
                let endNo = this.$refs.endNo.value;
                if (value && !Number.isInteger(value)) callback('起始号段只能输入数字');
                else if (value && Number.isInteger(value) && !endNo) callback('请输入结束号段');
                else if (endNo && !Number.isInteger(endNo)) callback('结束号段只能输入数字');
                else if (endNo && Number.isInteger(endNo) && !value) callback('请输入起始号段');
                else callback();
                // else if(Number.isInteger(value)&&Number.isInteger(endNo))callback();
              }, trigger: 'blur'
            }
          ]
        },
        fileName: '',
        list: [],
        page: 1,
        pageSize: 10,
        total: 0,
        tableLoading: false,
        dialogFormVisible: false,
        dialogTableVisible: false,
        excelDialogVisible: false,
        errorList: [],
        errorPage: 1,
        errorTotle: 0,
        batchOpratorId: '',
        exlList: [],  //可下载表格列表
        exlLength: 0,
      }
    },
    mounted() {
      this.innitMealData();
      this.innitAccountData();
      this.innitBalanceData();
      this.innitData();
    },
    methods: {
      //下载设备二维码
      async downLoadQRCode(row){
        window.location.href = `/api/batch-job-center/batch-oprator-record/disorderExcel/download/white?id=${row.id}`;
      },
      //下载行内数据内所有卡号数据
      async downLoadData(row){
        window.location.href = `/api/batch-job-center/batch-oprator-record/exportCardListExcel/white?id=${row.id}`;
      },
      //查看失败数据
      checkErrorData(row){
        this.dialogTableVisible = true;
        this.batchOpratorId = row.id;
        this.getErrorData();

      },
      openExcelDialog(row){
        this.excelDialogVisible = true;
        this.exlLength = row.allCount;
        excelRecords({batchOpratorId: row.id}).then(res=>{
          this.exlList = res.data
        })
      },
      getErrorData(){
        let returnData = cardNumberRecords({ batchOpratorId: this.batchOpratorId,page:{current: this.errorPage.toString(),size:10} }).then(returnData=>{
          if(returnData._result){
            this.errorList = returnData.data.records.length>0?returnData.data.records:[];
            this.errorTotle = returnData.data.total
          }
        })
      },
      changeErrorPage(val){
        this.errorPage = val;
        this.getErrorData();
      },
      CopyRemark(message){
        let that = this
        this.$copyText(message).then(function (e) {
          that.$message.success('复制成功')
          // console.log(e)
        }, function (e) {
          that.$message.fail('复制失败')
          // console.log(e)
        })
      },
      async innitData() {
        let setMealHeadId = this.form.mealType; //套餐大类
        let balanceHeadId = this.form.balancePackage;//余额套餐
        let accountId = this.form.passage;//通道类型
        let oprationStatus = this.form.operationStatus;//操作状态
        let oprationType = this.form.operationType;//操作状态
        let insertTimeStart = '';
        let insertTimeEnd = '';
        if (setMealHeadId == '0') setMealHeadId = '';
        if (balanceHeadId == '0') balanceHeadId = '';
        if (accountId == '0') accountId = '';
        if (oprationType == '0') oprationType = '';
        if (oprationStatus == '0') oprationStatus = '';
        if (this.form.dateRange) {
          insertTimeStart = this.form.dateRange[0];
          insertTimeEnd = this.form.dateRange[1];
        }
        this.tableLoading = true;
        const returnData = await BulkOperateCardsRecords({
            setMealHeadId: setMealHeadId,
            balanceHeadId: balanceHeadId,
            accountId: accountId,
            insertTimeStart: insertTimeStart,
            insertTimeEnd: insertTimeEnd,
            oprationStatus: oprationStatus,
            dictOprationType: oprationType,
            empName: this.form.operatorName,
            loginName: this.form.loginName,
            page: {
              current: this.page.toString(),
              size: this.pageSize.toString()
            }
          },
          {
            obj: this,
            key: 'tableLoading'
          });
        if (returnData._result) {
          this.list = [];
          this.total = 0;
          if (returnData.data.records) {
            this.list = returnData.data.records;
            this.total = returnData.data.total;
          }
        }
        this.tableLoading = false;
      },
      saveOperationType(){
        this.dialogFormVisible = false;

        for(let item of this.operationTypeOptions){
          if(item.value == this.form.operationType){
            this.form.operationTypeName = item.label;
          }
        }
      },
      changPage(val) {
        this.page = val;
        this.innitData();
      },
      changeSize(val){
        this.pageSize = val;
        this.page = 1;
        this.innitData();
      },
      async innitAccountData() {
        //通道下拉
        const returnData2 = await initAccountSelect({});
        this.passageOptions = [
          {value: '0', label: '请选择通道'}
        ];
        if (returnData2._result) {
          for (let item of returnData2.data) {
            let obj = {};
            obj.value = item.id;
            obj.label = item.accountName;
            this.passageOptions.push(obj)
          }
          this.form.passage = '0';
        }
      },
      async innitBalanceData() {
        //余额套餐下拉
        const returnData3 = await getbalanceHeadSelect({});
        this.balancePackageOptions = [
          {value: '0', label: '请选择余额套餐'}
        ];
        if (returnData3._result) {
          for (let item of returnData3.data) {
            let obj = {};
            obj.value = item.id;
            obj.label = item.headName;
            this.balancePackageOptions.push(obj);
          }
          this.form.balancePackage = '0';
        }
      },
      async innitMealData() {
        //套餐大类下拉
        const returnData1 = await initSetMealHeadSelect({})
        this.mealTypeOptions = [
          {value: '0', label: '请选择套餐大类'}
        ];
        if (returnData1._result) {
          for (let item of returnData1.data) {
            const obj = {};
            obj.value = item.id;
            obj.label = item.name;
            this.mealTypeOptions.push(obj)
          }
          this.form.mealType = '0';
        }
      },
      //获取代理账号列表
      querySearchAsync(){
        getAgentId({}).then(res=>{
          if(res.data){

          }
        })
      },
      async querySearch(queryString, cb) {
        let returnData = await getLoginName({
          loginname: this.form.loginName
        });
        if (returnData._result) {
          this.loginNames = [];
          for (let item of returnData.data) {
            this.loginNames.push({'value': item})
          }
        }
        cb(this.loginNames);
      },
      handleSelect(val){

      },
      // uploadExl() {
      //   let event = event || window.event;
      //   this.file = event.target.files[0];
      //   this.fileName = this.file.name;
      //   // console.log('-----uploadExl-----')
      //   // console.log(this.file)
      // },
      // delFile() {
      //   this.form.file = '';
      //   this.file = {};
      //   this.fileName = '';
      // },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.form.endNo = null;
        this.form.operationType = '0';
        this.fileList = [];
        this.form.url = '';
      },
    }
  }
</script>

<style scoped>
  .uploadFile {
    width: 120px;
    height: 36px;
    position: absolute;
    opacity: 0;
    left: 0;
    top: 0;
    z-index: 100;
  }
  .shotRemark{
    width: 180px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .el-dropdown-menu--medium .el-dropdown-menu__item {
    padding: 0;
  }
  .operation {
    width: 100%;
    height: 30px;
    line-height: 30px;
    border: 0;
    outline: none;
    display: block;
    text-align: center;
    margin: 0;
    padding: 0 17px;
  }

</style>
<style>
  .el-dropdown-link {
    cursor: pointer;
    color: var(--lightBg) !important;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
</style>
<!--<el-row>-->
<!--<el-col :span="8">-->
<!--<el-form-item label="号段" prop="startNo">-->
<!--<el-input v-model.number="form.startNo" ref="startNo" style="width: 150px;"></el-input>-->
<!--<span style="margin: 0 10px;">&#45;&#45;</span>-->
<!--<el-input v-model.number="form.endNo" ref="endNo" style="width: 150px" ></el-input>-->
<!--</el-form-item>-->
<!--</el-col>-->
<!--<el-col :span="16">-->
<!--<el-form-item label="不规则号码" prop='file'>-->
<!--<el-input type="file" v-model="form.file" @change="uploadExl" class="uploadFile" accept=".xls,.xlsx"></el-input>-->
<!--<el-button type="primary"><i class="el-icon-upload"></i> 选择Excel文件</el-button>-->
<!--<transition name="el-fade-in-linear"><span style="margin: 0 10px; color: #666" v-if="fileName">文件名称：<span style="color: #11b95c; margin-right: 20px">{{fileName}}</span> <i class="el-icon-delete" style="color: firebrick" @click="delFile"></i> </span></transition>-->
<!--&lt;!&ndash;<span style="margin: 0 10px; color: #666">仅限.xls/.xlsx文件</span>&ndash;&gt;-->
<!--</el-form-item>-->
<!--</el-col>-->
<!--</el-row>-->
<!--<el-row>-->
<!--<el-form-item label="卡状态" prop="cardStatus">-->
<!--<el-checkbox-group v-model="form.cardStatus">-->
<!--<el-checkbox v-for="item in cardStatusOptions" :label="item.label" :key="item.value">{{item.value}}</el-checkbox>-->
<!--</el-checkbox-group>-->
<!--</el-form-item>-->
<!--</el-row>-->
